<!-- system/user/index.vue - 用户管理页面 -->
<template>
  <div class="user-management-container">
    <!-- 🎯 搜索工具栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="RefreshRight" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 🎯 操作工具栏 -->
    <el-card class="toolbar-card" shadow="never">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-button type="primary" :icon="Plus" @click="handleAdd">
            新增用户
          </el-button>
          <el-button
            type="danger"
            :icon="Delete"
            :disabled="!selectRows.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button :icon="Download" @click="handleExport">
            导出数据
          </el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button circle :icon="RefreshRight" @click="loadData" title="刷新" />
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 🎯 VXE Table 表格 -->
    <el-card class="table-card" shadow="never">
      <vxe-table
        ref="xTable"
        :data="tableData"
        :loading="loading"
        border
        stripe
        resizable
        highlight-hover-row
        show-overflow
        :row-config="{ isHover: true }"
        :column-config="{ resizable: true }"
        :checkbox-config="{ reserve: true }"
        @checkbox-change="handleCheckboxChange"
        @checkbox-all="handleCheckboxChange"
        height="600"
      >
        <!-- 复选框列 -->
        <vxe-column type="checkbox" width="60" align="center" fixed="left" />
        
        <!-- 序号列 -->
        <vxe-column type="seq" title="序号" width="70" align="center" fixed="left" />
        
        <!-- 用户名 -->
        <vxe-column field="username" title="用户名" min-width="120" sortable>
          <template #default="{ row }">
            <el-tag type="primary" effect="plain">{{ row.username }}</el-tag>
          </template>
        </vxe-column>
        
        <!-- 真实姓名 -->
        <vxe-column field="realName" title="真实姓名" min-width="100" sortable />
        
        <!-- 手机号 -->
        <vxe-column field="phone" title="手机号" min-width="120" />
        
        <!-- 邮箱 -->
        <vxe-column field="email" title="邮箱" min-width="180" show-overflow />
        
        <!-- 角色 -->
        <vxe-column field="role" title="角色" min-width="120">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role"
              style="margin-right: 4px"
              size="small"
            >
              {{ getRoleName(role) }}
            </el-tag>
          </template>
        </vxe-column>
        
        <!-- 部门 -->
        <vxe-column field="department" title="部门" min-width="120" />
        
        <!-- 状态 -->
        <vxe-column field="status" title="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </vxe-column>
        
        <!-- 创建时间 -->
        <vxe-column field="createTime" title="创建时间" min-width="160" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </vxe-column>
        
        <!-- 操作列 -->
        <vxe-column title="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-button
              type="info"
              link
              :icon="View"
              @click="handleView(row)"
            >
              详情
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>
      
      <!-- 🎯 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        </div>
      </el-card>
    
    <!-- 🎯 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="formData.realName"
            placeholder="请输入真实姓名"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="formData.roles"
            placeholder="请选择角色"
            multiple
            style="width: 100%"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="编辑" value="editor" />
            <el-option label="访客" value="visitor" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="部门" prop="department">
          <el-input
            v-model="formData.department"
            placeholder="请输入部门"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 🎯 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="用户详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名">
          {{ currentRow.username }}
        </el-descriptions-item>
        <el-descriptions-item label="真实姓名">
          {{ currentRow.realName }}
        </el-descriptions-item>
        <el-descriptions-item label="手机号">
          {{ currentRow.phone }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          {{ currentRow.email }}
        </el-descriptions-item>
        <el-descriptions-item label="角色" :span="2">
          <el-tag
            v-for="role in currentRow.roles"
            :key="role"
            style="margin-right: 4px"
          >
            {{ getRoleName(role) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="部门">
          {{ currentRow.department }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentRow.status === 1 ? 'success' : 'danger'">
            {{ currentRow.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(currentRow.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="最后登录时间" :span="2">
          {{ formatDate(currentRow.lastLoginTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  RefreshRight,
  Plus,
  Delete,
  Edit,
  View,
  Download
} from '@element-plus/icons-vue'
import XEUtils from 'xe-utils'

// 🎯 表格实例
const xTable = ref(null)

// 🎯 状态
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const selectRows = ref([])
const dialogVisible = ref(false)
const detailVisible = ref(false)
const isEdit = ref(false)
const currentRow = ref({})

// 🎯 搜索表单
const searchForm = reactive({
  username: '',
  phone: '',
  status: undefined
})

// 🎯 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 🎯 表单数据
const formData = reactive({
  username: '',
  realName: '',
  password: '',
  phone: '',
  email: '',
  roles: [],
  department: '',
  status: 1
})

// 🎯 表单校验规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const formRef = ref(null)

// 🎯 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')

// 🎯 初始化
onMounted(() => {
  loadData()
})

// 🎯 加载数据
async function loadData() {
  loading.value = true
  
  try {
    // 模拟 API 请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = generateMockData()
    
    // 分页处理
    const start = (pagination.page - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    
    tableData.value = mockData.slice(start, end)
    pagination.total = mockData.length
    
    ElMessage.success('数据加载成功')
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 🎯 生成模拟数据
function generateMockData() {
  const data = []
  const departments = ['技术部', '产品部', '运营部', '市场部', '财务部']
  const roles = [['admin'], ['editor'], ['visitor'], ['admin', 'editor']]
  
  for (let i = 1; i <= 100; i++) {
    data.push({
      id: i,
      username: `user${i}`,
      realName: `用户${i}`,
      phone: `138${String(i).padStart(8, '0')}`,
      email: `user${i}@example.com`,
      roles: roles[i % roles.length],
      department: departments[i % departments.length],
      status: i % 3 === 0 ? 0 : 1,
      createTime: new Date(2024, 0, i).toISOString(),
      lastLoginTime: new Date(2025, 0, i).toISOString()
    })
  }
  
  return data
}

// 🎯 搜索
function handleSearch() {
  pagination.page = 1
  loadData()
}

// 🎯 重置
function handleReset() {
  searchForm.username = ''
  searchForm.phone = ''
  searchForm.status = undefined
  handleSearch()
}

// 🎯 复选框变化
function handleCheckboxChange() {
  selectRows.value = xTable.value.getCheckboxRecords()
}

// 🎯 新增
function handleAdd() {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 🎯 编辑
function handleEdit(row) {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(formData, row)
}

// 🎯 删除
function handleDelete(row) {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.username}" 吗？`,
    '删除确认',
    {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消'
    }
  ).then(() => {
    // 模拟删除
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 🎯 批量删除
function handleBatchDelete() {
  if (!selectRows.value.length) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectRows.value.length} 个用户吗？`,
    '批量删除确认',
    {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消'
    }
  ).then(() => {
    // 模拟批量删除
    selectRows.value.forEach(row => {
      const index = tableData.value.findIndex(item => item.id === row.id)
      if (index > -1) {
        tableData.value.splice(index, 1)
        pagination.total--
      }
    })
    
    xTable.value.clearCheckboxRow()
    selectRows.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 🎯 查看详情
function handleView(row) {
  currentRow.value = row
  detailVisible.value = true
}

// 🎯 状态变化
function handleStatusChange(row) {
  ElMessage.success(`用户 ${row.username} 状态已${row.status === 1 ? '启用' : '禁用'}`)
}

// 🎯 提交表单
function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      
      // 模拟提交
      setTimeout(() => {
        if (isEdit.value) {
          // 更新
          const index = tableData.value.findIndex(item => item.id === formData.id)
          if (index > -1) {
            Object.assign(tableData.value[index], formData)
          }
          ElMessage.success('更新成功')
        } else {
          // 新增
          tableData.value.unshift({
            ...formData,
            id: Date.now(),
            createTime: new Date().toISOString(),
            lastLoginTime: new Date().toISOString()
          })
          pagination.total++
          ElMessage.success('新增成功')
        }
        
        dialogVisible.value = false
        submitLoading.value = false
      }, 500)
    }
  })
}

// 🎯 对话框关闭
function handleDialogClose() {
  formRef.value?.resetFields()
  resetForm()
}

// 🎯 重置表单
function resetForm() {
  Object.assign(formData, {
    username: '',
    realName: '',
    password: '',
    phone: '',
    email: '',
    roles: [],
    department: '',
    status: 1
  })
}

// 🎯 导出数据
function handleExport() {
  if (!tableData.value.length) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  
  // 使用 VXE Table 的导出功能
  xTable.value.exportData({
    filename: '用户列表',
    type: 'csv',
    isHeader: true,
    mode: 'current'
  })
  
  ElMessage.success('导出成功')
}

// 🎯 分页变化
function handleSizeChange(size) {
  pagination.pageSize = size
  loadData()
}

function handleCurrentChange(page) {
  pagination.page = page
  loadData()
}

// 🎯 工具函数
function formatDate(dateStr) {
  if (!dateStr) return '-'
  return XEUtils.toDateString(dateStr, 'yyyy-MM-dd HH:mm:ss')
}

function getRoleName(role) {
  const roleMap = {
    admin: '管理员',
    editor: '编辑',
    visitor: '访客'
  }
  return roleMap[role] || role
}
</script>

<style lang="scss" scoped>
.user-management-container {
  .search-card,
  .toolbar-card,
  .table-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 16px;
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
}

// 🎯 VXE Table 样式调整
:deep(.vxe-table) {
  .vxe-body--row.row--hover {
    background-color: var(--el-fill-color-light);
  }
  
  .vxe-table--header-wrapper {
    background-color: var(--el-fill-color-lighter);
  }
}
</style>
